An exception is an event that disrupts the normal flow of a program at runtime. Think of it as a "warning light" that signals something went wrong, allowing the program to handle it gracefully instead of crashing.
Exceptions are like "speed bumps" in your code. They slow down or stop execution unless you handle them properly!
Imagine you're cooking:
In Java, dividing by zero triggers an ArithmeticException that you handle similarly.
int a = 10;
int b = 0;
int result = a / b; // Throws ArithmeticException: divide by zero
Q: What happens if an exception is not caught?
A: The program terminates, and the JVM prints the stack trace. Try running the above code to see!
The Throwable class is the root of Java’s exception hierarchy. All exceptions and errors inherit from it, like the "trunk" of a family tree.
Fallback Text Diagram (if image fails):
Throwable
├── Exception
│ ├── Checked Exceptions (e.g., IOException, SQLException)
│ └── RuntimeException (Unchecked, e.g., NullPointerException)
└── Error (e.g., OutOfMemoryError, StackOverflowError)
Mnemonic: Checked exceptions are like "boarding passes" – you must show (handle/declare) them before compiling.
try-catch or declared with throws.IOException, SQLException, FileNotFoundException.Mnemonic: Unchecked exceptions are like "pop quizzes" – they surprise you at runtime.
NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.Mnemonic: Errors are like "server crashes" – too severe to fix in code.
StackOverflowError: Infinite recursion.OutOfMemoryError: No heap space.VirtualMachineError: JVM issues.Q: Is IOException checked or unchecked?
A: Checked – must be handled or declared.
The backbone of exception handling: try for risky code, catch for handling errors, finally for cleanup.
Fallback Text Diagram (if image fails):
[Start] → [Try: Risky Code]
├── Exception → [Catch: Handle It]
└── [Finally: Cleanup]
[End]
try {
// Risky code
} catch (ExceptionType e) {
// Handle exception
} finally {
// Cleanup (always runs)
}
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Cleanup done!");
}
Output:
Cannot divide by zero!
Cleanup done!
Mnemonic: Try = Test drive, Catch = Fix flat tire, Finally = Return car keys.
Q: Does finally execute if System.exit() is called?
A: No, it’s skipped on JVM shutdown.
Key for controlling exceptions manually or warning about them.
Fallback Text Diagram (if image fails):
throw: Actively throws an exception object
throws: Declares possible exceptions in method signature
Easy Explanation:
throw: "I’m throwing this error now!" (Action).throws: "Heads up, this method might throw errors!" (Warning).| Keyword | Meaning | Used In | Exceptions |
|---|---|---|---|
throw |
Manually throw | Method body | One at a time |
throws |
Declare | Method signature | Multiple |
void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Underage!");
}
}
void readFile() throws IOException {
FileReader fr = new FileReader("file.txt");
}
Mnemonic: Throw = Toss the ball, Throws = Warn others to catch it.
Q: Can throws list unchecked exceptions?
A: Yes, but it’s optional since they’re not enforced by the compiler.
Create tailored exceptions for specific scenarios, extending Exception (checked) or RuntimeException (unchecked).
Mnemonic: Custom exceptions are like "customized warning signs" for your app’s unique issues.
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
}
}
void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age too low!");
}
}
Q: Should custom exceptions extend Exception or RuntimeException?
A: Depends: Exception for checked, RuntimeException for unchecked.
These sound similar but are distinct – a favorite interview topic!
| Concept | Key Notes |
|---|---|
| Throwable | Root: Exception (checked/unchecked), Error |
| Checked Exception | Compile-time; must handle/declare |
| Unchecked | Runtime; optional to handle |
| throw | Manually throw exception |
| throws | Declare in signature |
| finally | Always executes |
| finalize() | GC cleanup (deprecated) |
| try-with-resources | Auto-close resources |
Commonly asked in companies like Google, Amazon, Microsoft, etc.
A: Checked: Compile-time, must handle/declare (e.g., IOException). Unchecked: Runtime, optional (e.g., NullPointerException).
A: Throwable → Exception (Checked: IOException, Unchecked: RuntimeException) & Error (OutOfMemoryError). See hierarchy diagram above.
A: Yes, with finally or in try-with-resources.
A: It propagates up the call stack; if unhandled, JVM terminates with stack trace.
A: Rarely – they indicate severe issues (e.g., OutOfMemoryError).
A: Calls close() in a hidden finally block.
A: final: Locks variables/methods/classes. finally: Cleanup block. finalize(): Deprecated GC method.
A: For domain-specific errors to improve code clarity.
A: Yes, specific (subclass) to general (superclass) order.
A: Unhandled exceptions move up the call stack to be handled or crash the program.